import { PageContainer } from "@ant-design/pro-layout"
import ProTable, { ActionType } from "@ant-design/pro-table"
import { AddonMenuSelectorButton, IconSelectorButton, SkerIcon, useForm, useModal, useModel, useProTable } from "@sker/sdk"
import { renderAdminPage, useServerData } from "@sker/ui"
import { SysMenu } from "@sker/model"
import { Button, Card, Modal, Popconfirm } from "antd"
import { PlusOutlined } from "@ant-design/icons"
import { BetaSchemaForm } from "@ant-design/pro-form"
import { useEffect, useRef, useState } from "react"

export const MenuSelector: React.FC<{ value: string[], onSelect: (keys: string,selected: boolean) => void }> = ({ value, onSelect }) => {
    const model = useModel(SysMenu)
    const { props: addMenuModal, setOpen: setAddMenuModalOpen } = useModal('添加菜单')
    const [parent, setParent] = useState<any>()
    const { props: addMenuFormProps, form } = useForm([
        {
            title: '是否分组',
            valueType: 'switch',
            dataIndex: 'is_group'
        },
        {
            dataIndex: 'icon',
            fieldProps: {
                rules: [{ required: true, message: '标题必填' }]
            },
            renderFormItem(schema, config, form, action) {
                const value = form.getFieldValue('icon')
                return <IconSelectorButton value={value} onChange={e => {
                    form.setFieldValue('icon', e)
                }} />
            },
        },
        {
            valueType: 'dependency',
            name: ['is_group'],
            columns({ is_group }) {
                if (is_group) {
                    return [{
                        title: '标题',
                        dataIndex: 'title',
                        fieldProps: {
                            rules: [{ required: true, message: '标题必填' }]
                        }
                    }, {
                        title: '英文名',
                        dataIndex: 'name',
                        tooltip: '唯一',
                        fieldProps: {
                            rules: [{ required: true, message: '标题必填' }]
                        }
                    }]
                }
                return [{
                    dataIndex: 'url',
                    fieldProps: { hidden: true },
                    formItemProps: { hidden: true }
                }, {
                    dataIndex: 'main',
                    fieldProps: { hidden: true },
                    formItemProps: { hidden: true }
                }, {
                    renderFormItem(schema, config, form, action) {
                        const url = form.getFieldValue('url')
                        return <AddonMenuSelectorButton value={url} onChange={(link, main, title, name) => {
                            form.setFieldValue('url', link)
                            form.setFieldValue('main', main)
                            form.setFieldValue('title', title)
                            form.setFieldValue('name', name)
                        }} />
                    },
                }, {
                    title: '标题',
                    dataIndex: 'title',
                    fieldProps: {
                        rules: [{ required: true, message: '标题必填' }]
                    }
                }, {
                    title: '代号',
                    dataIndex: 'name',
                    tooltip: '唯一',
                    fieldProps: {
                        rules: [{ required: true, message: '代号必填' }]
                    }
                }]
            },
        }
    ], async (values) => {
        if (values.is_group) {
            const data: any = {
                role: null,
                name: values.name,
                title: values.title,
                icon: values.icon,
                url: null,
                pname: parent?.name,
                displayorder: 0,
                main: null
            }
            if (record) {
                data.id = record?.id;
            }
            await model.save(data)
        } else {
            const data: any = {
                role: null,
                name: values.name,
                title: values.title,
                icon: values.icon,
                url: values.url,
                pname: parent?.name,
                displayorder: 0,
                main: values.main
            }
            if (record) {
                data.id = record?.id;
            }
            await model.save(data)
        }
        setRecord(null)
        setAddMenuModalOpen(false)
        actionRef.current?.reload();
    })
    const [record, setRecord] = useState<any>()
    const actionRef = useRef<ActionType>()
    const { props: tableProps, onChange, setSelectedRowKeys, onSelect: onTableSelect } = useProTable('checkbox', value)
    useEffect(() => {
        if(!value) return;
        setSelectedRowKeys(value)
    }, [value])
    onTableSelect((record, selected)=>{
        onSelect(record.name, selected)
    })
    useEffect(() => {
        if (!record) {
            form.resetFields()
            return;
        }
        record.is_group = !record.url
        form.setFieldsValue(record)
    }, [record])
    return <>
        <Modal {...addMenuModal} width={'600px'}>
            <BetaSchemaForm {...addMenuFormProps} />
        </Modal>
        <Card extra={<Button type={'primary'} icon={<PlusOutlined />} onClick={e => {
            setParent(null)
            setRecord(null)
            setAddMenuModalOpen(true)
        }}>添加</Button>}>
            <ProTable
                search={false}
                actionRef={actionRef}
                rowKey={record => {
                    return record.name
                }}
                toolBarRender={false}
                expandable={{
                    rowExpandable: (row) => row.children?.length > 0,
                }}
                columns={[
                    { title: '菜单名', dataIndex: 'title' },
                    { title: '唯一', dataIndex: 'name' },
                    {
                        title: '图标',
                        dataIndex: 'icon',
                        render(dom, entity, index, action, schema) {
                            return <SkerIcon width={'32px'} height={'32px'} name={entity.icon} />
                        },
                    },
                    {
                        title: '操作',
                        align: 'right',
                        render(dom, entity, index, action, schema) {
                            return <>
                                {!entity.pname && <Button size={'small'} type={'link'} onClick={e => {
                                    setParent(entity)
                                    setRecord(null);
                                    setAddMenuModalOpen(true)
                                }}>下级</Button>}
                                <Button size={'small'} type={'link'} onClick={e => {
                                    setAddMenuModalOpen(true)
                                    setRecord(entity)
                                }}>编辑</Button>
                                <Popconfirm onConfirm={async e => {
                                    await model.delete(entity.id)
                                    await actionRef.current?.reload();
                                }} title={'此操作不可逆!您确定要执行此操作吗？'} description={'删除后无法恢复，请慎重操作！！'}>
                                    <Button size={'small'} type={'link'} danger>删除</Button>
                                </Popconfirm>
                            </>
                        },
                    }
                ]}
                request={async (params) => {
                    return model.find(['id', 'title', 'icon', 'name', 'pname', { children: ['id', 'pname', 'title', 'icon', 'name'] }], [
                        { field: 'pname', operator: 'null', value: true }
                    ], [{ field: 'displayorder', order: 'asc' }], {
                        current: params.current,
                        pageSize: params.pageSize
                    })
                }}
                {...tableProps}
            />
        </Card>
    </>
}
